<?php namespace simpleFlow\model;

/**
 * Model for postgres tables
 * @package simpleFlow
 * @subpackage model
 * @author Guilherme Fontenele
 */
class ModelPgsql extends Model
{
	/**
	 * Constructor
	 */
	public function __construct()
	{
		parent::__construct();
		//self::$objConnection->getLink()->setAttribute(\PDO::ATTR_AUTOCOMMIT, FALSE);
	}
	
	/**
	 * Create read sql query
	 * @param integer $intKey Primary Key value
	 * @param string $strAlias Alias name
	 * @return string Query
	 */
	protected function __createReadSql($intKey,$strAlias = null)
	{
		$strAliasClausules = $strAlias ? $strAlias.'.' : null;
		$strSql = "SELECT {$this->__getFields($strAlias)} FROM {$this->_table} {$strAlias} WHERE {$strAliasClausules}{$this->_primaryKey}";
		$strSql.= $intKey ? " = '{$intKey}'" : " IS NULL";
		return $strSql;
	}
	
	/**
	 * Create read all sql query
	 * @param string $strAlias Alias name
	 * @param integer $intPage Number of page
	 * @param integer $intOffset Number of offset
	 * @return string Query
	 */
	protected function __createReadAllSql($strAlias = null,$intPage = null,$intOffset = SF_VIEW_LIST_ROWS)
	{
		$strAliasClausules = $strAlias ? $strAlias.'.' : null;
		$strSql = "SELECT {$this->__getFields($strAlias)} FROM {$this->_table} {$strAlias} ORDER BY {$strAliasClausules}{$this->_primaryKey}";
		if($intPage) { $strSql.= " LIMIT {$intOffset} OFFSET ".(($intPage * $intOffset) - $intOffset); }
		return $strSql;
	}
	
	/**
	 * Create count sql query
	 * @param string $strAlias Alias name
	 * @param integer $intPage Number of page
	 * @param integer $intOffset Number of offset
	 * @return string Query
	 */
	protected function __createCountAllSql($strAlias = null,$intPage = null,$intOffset = SF_VIEW_LIST_ROWS)
	{
		$strAliasClausules = $strAlias ? $strAlias.'.' : null;
		$strSql = "SELECT COUNT({$this->_primaryKey}) AS total FROM {$this->_table} {$strAlias}";
		if($intPage) { $strSql.= " LIMIT {$intOffset} OFFSET ".(($intPage * $intOffset) - $intOffset); }
		return $strSql;
	}
	
	/**
	 * Create search sql query
	 * @param array $arrFilter Filters
	 * @param string $strAlias Alias name
	 * @return string Query
	 */
	protected function __createSearchSql($arrFilter = array(),$strAlias = null)
	{
		$strSql = "SELECT {$this->__getFields($strAlias)} FROM {$this->_table}";
		if(count($arrFilter))
		{
			$strSql.= " WHERE ";
			$strAnd = '';
			foreach($arrFilter as $_intKey => $_value)
			{
				//TODO: verificar tipo do campo para colocar ou não as aspas
				$strSql.= "{$strAnd}{$this->_config['model'][$_intKey]} = '{$_value}'";
				$strAnd.= ' AND ';
			}
		}
		return $strSql;
	}
	
	/**
	 * Create insert sql query
	 * @param integer $intKey Primary Key value
	 * @return string Query
	 */
	protected function __createInsertSql($intKey = null)
	{
		$strSql = "INSERT INTO {$this->_table} ({$this->__getFields(null,$intKey ? false : true)}) VALUES (";
		foreach($this->_config['model'] as $_nmAttribute => $_nmField)
		{
			if($this->_primaryKey != $_nmField)
			{
				switch($this->_config['_fields'][$_nmAttribute]['type'])
				{
					case 'character varying':
						$_fieldValue = "'{$this->$_nmAttribute}'";
						break;
					default:
						$_fieldValue = $this->$_nmAttribute;
						break;
				}
				
				$strSql.= "{$_fieldValue}, ";
			}
		}
		$strSql = \substr($strSql,0,\strlen($strSql)-2);
		$strSql.= ")";
		return $strSql;
	}
	
	/**
	 * Get fields for select in query
	 * @param string $strAlias Alias name
	 * @param boolean $removePrimaryKey If wants to remove primary key from fields
	 * @return string Fields for select in query
	 */
	protected function __getFields($strAlias = null,$removePrimaryKey = false)
	{
		$strFields = '';
		if($strAlias) { $strAlias.='.'; }
		foreach($this->_config['model'] as $_nmField)
		{
			if(($removePrimaryKey && $_nmField != $this->_primaryKey) || !$removePrimaryKey)
			{
				$strFields.= $strAlias.$_nmField.', ';
			}
		}
		return \substr($strFields,0,\strlen($strFields)-2);
	}
	
	/**
	 * Get clausules
	 * @param type $strAlias 
	 * @todo I dont remember for what i created this
	 */
	protected function __getClausules($strAlias = null)
	{
		
	}
	
	/**
	 * Clean the field value and prevents from sql injects
	 * @param string $strValue Value
	 * @return Value cleaned
	 */
	public function washField($strValue)
	{
		return pg_escape_string(htmlspecialchars(stripslashes($strValue)));
	}
}

?>